<template>
  <div style="float: left;margin-top: 5px">
    <el-form ref="menuSearchRef" :model="searchFormData">
      <el-form-item label="关键词" >
        <el-input  type="text" v-model="searchFormData.name"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div style="height: 40px;margin-top: 5px;float: left;margin-left: 20px;">
    <el-button @click="searchDicClick">查询</el-button>
    <el-button @click="resetSearchClick">重置</el-button>
    <el-button v-check-permission="'system:menu:add'" @click="addDicClick">新增</el-button>
  </div>
  <div style="clear: both"></div>
  <div style="height: calc(100% - 60px);">
    <Table  :show-page="false" ref="tableRef" :show-line-number="true"
           :showCheckBox="false" :url="permissionGridUrl" :columns="columns"  :table-model="TableModel.TREE"  :tree-config="treeModelConfig">
      <template  v-slot:handle="slotProps">
        <el-button v-check-permission="'system:menu:update'" @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">编辑</el-button>
        <el-button v-check-permission="'system:menu:delete'" @click.stop="deleteTableRowData(slotProps.rowData,slotProps.rowIndex)">删除</el-button>
      </template>
    </Table>
  </div>
  <DialogForm ref="menuEditFormRef" :form="menuForm" title="编辑权限" @validateSuccess="validateSuccess" :data-change="dataChange">
    <template v-slot:parentTree="slotProps">
      <el-tree ref="selectTree" :data="menuTreeData" :props="menuTreeOptions" node-key="id" :show-checkbox="true"  :check-strictly="true"  @check="handleCheckChange">
      </el-tree>
    </template>
  </DialogForm>
</template>

<script setup >

import Table from "@/components/plugs/table/Table.vue";
import {getCurrentInstance, inject, nextTick, onMounted, reactive, ref, toRaw, useSlots} from "vue";
import DialogForm from "@/components/plugs/form/DialogForm.vue";
import {FormItemType} from "@/components/plugs/form/DialogFormInterface.js";
import {AXIOS_NAME} from '@/constant/constant.js'
import {ElMessage} from "element-plus";
import {assembleTreeData} from "@/utils/useTreeData.js";
import {deleteRow, HandleEnum} from "@/utils/utils.ts";
import {TableModel} from "@/components/plugs/table/TableInterface.js";
import {ExpandedModel} from "@/components/plugs/tree/TreeView.js";
import FileUpload from "@/components/plugs/upload/FileUpload.vue";
import {ChoiceWay} from "@/components/plugs/upload/UploadInterface.js";
import SearchInput from "@/components/plugs/input/SearchInput.vue";
import SearchSelect from "@/components/plugs/select/SearchSelect.vue";

const searchInputRef = ref(null);
const menuSearchRef = ref(null);
const selectTree = ref(null);
const tableRef = ref(null);
const $axios = inject(AXIOS_NAME);
const permissionGridUrl = ref("/menu/getAllPermission");
const menuEditFormRef = ref(null);
const fileUploadRef = ref(null);

const uploadFileClick = () =>{
  fileUploadRef.value.show();
}

const uploadSuccess = (state,data) =>{
}

const paramFormat = (value) => {
  return {"name":value};
}

const searchFormData = reactive({
  "name": ''
})
let menuTreeData = reactive([]);
const menuTreeOptions = {
  "label": 'name'
}

const columns = [
  {field:"name","desc": "名称"},
  {field:"icon","desc": "图标"},
  {field:"path","desc": "路由/按钮标识"},
  {field:"type","desc": "类型",dicType:'perssion_type'},
  {field:"startUsing","desc": "状态",dicType:'start_using'},
  {field:"sort","desc": "排序"},
  {field:"showTime","desc": "创建时间",width: 200},
  {field:"handle","desc": "操作",isSlot:true,width:200}
];

const path = reactive({type: FormItemType.INPUT_TEXT,label: '路由',name: 'path'});
let items = [];
items.push({type: FormItemType.INPUT_HIDDEN,label: 'id',name: 'id'});
items.push({type: FormItemType.INPUT_TEXT,label: '名称',name: 'name'});
items.push({type: FormItemType.INPUT_TEXT,label: '图标',name: 'icon'});
items.push(path);
items.push({type: FormItemType.CUSTOMIZE_SELECT,label: '类型',name: 'type',
  url: '/dictionary/getDicDataByGroupId?groupId=perssion_type',textFiled:'text',valueField: "val",defaultValue:'1'});
items.push({type: FormItemType.CUSTOMIZE_SELECT,label: '状态',name: 'startUsing',
  url: '/dictionary/getDicDataByGroupId?groupId=start_using',textFiled:'text',valueField: "val",defaultValue:'1'});
items.push({type: FormItemType.INPUT_NUMBER,label: '排序',name: 'sort'});
items.push({type: FormItemType.SLOT,label: '父级',name:'parentTree'});

let treeModelConfig = {
  idField:"id",
  pIdField:"pid",
  rootId:"0",
  expand: false,
  expandModel: ExpandedModel.SINGLE
}

let menuForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items:items,
  rules:{
    name: [
      { required: true, message: '请填写名字', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择类型', trigger: 'blur' }
    ],
    sort: [
      { required: true, message: '请填写排序', trigger: 'blur' }
    ]
  },
});


const validateSuccess = (data) =>{
  debugger;
  const checkedData = selectTree.value.getCheckedNodes();
  data.pid = '0';
  if(checkedData.length > 0){
    data.pid = checkedData[0].id;
  }
  $axios.post('/menu/addOrUpdatePermission',data).then((response) => {
    const data = response.data;
    if(data.code == -1){
      ElMessage.error("操作失败!");
      return;
    }
    tableRef.value.reload();
    menuEditFormRef.value.close();
  },(error) => {
    ElMessage.info("请求失败!")
  });
}

const searchDicClick = () =>{
  tableRef.value.reload(toRaw(searchFormData));
}

const resetSearchClick = () =>{
  searchFormData.name = "";
}

const addDicClick = () =>{
  menuEditFormRef.value.show();
  getMenuTreeData();
}

const editTableData = (rowData,rowIndex) =>{
  debugger;
  menuEditFormRef.value.show();
  menuEditFormRef.value.setData(rowData);
  if(rowData.pid != null && rowData.pid != undefined){
    nextTick(() => {
      selectTree.value.setCheckedKeys([rowData.pid]);
    });
  }
}

const deleteTableRowData = (rowData,rowIndex) =>{
  deleteRow('/menu/delete',rowData,function (state,data) {
    if(state == HandleEnum.SUCCESS){
      tableRef.value.reload();
    }
  });
}

const getMenuTreeData = () =>{
  menuTreeData.clear();
  $axios.post('/menu/getAllPermissionTree').then((response) => {
    const data = response.data;
    if(data.code = 1){
      let permissionData = data.data;
      menuTreeData.pushAll(assembleTreeData(data.data,'pid',"id",'0'));
    }
  },(error) => {

  });
}

const handleCheckChange = (node,checkObj) => {
  if (checkObj.checkedKeys.length != 0) {
    if (checkObj.checkedKeys.length == 2) {
      selectTree.value.setCheckedKeys([node.id]);
    }
  }
}
getMenuTreeData();

const dataChange = (oldValue,newValue,field,cRef) =>{
  if(field != 'type'){
    return;
  }
  menuEditFormRef.value.triggerField(['icon'],newValue == '1');
  if(newValue != '1'){
    menuForm.rules['path'] = [ { required: true, message: '请填写按钮标识', trigger: 'blur' }];
    path.label = '按钮标识';
  }else{
    delete menuForm.rules['path'];
    path.label = '路由';
  }
}
</script>

<style scoped>
</style>
